<?php

namespace web\api\controller;

use addons\member\model\MnemonicWords;
use FurqanSiddiqui\BIP39\BIP39;

class Register extends \web\common\controller\Controller {

    protected function _initialize() {
         header("Access-Control-Allow-Origin:*");
    }

    public function register(){
        if(IS_POST){
            $m = new \addons\member\model\MemberAccountModel();
            try {
                $phone = trim($this->_post('phone',true));
//                if (!preg_match("/^1[34578]{1}\d{9}$/", $phone)) return $this->failJSON('请输入正确的手机号');
                $password = trim($this->_post('password',true));
                $password1 = trim($this->_post('password1',true));
                $verify_code = trim($this->_post('verify_code',true));
                $country_code = $this->_post('country_code', true, 'int')??86;
                $pay_password = trim($this->_post('pay_password',true));
                $pay_password1 = trim($this->_post('pay_password1',true));
                if ($country_code == '00886' || $country_code == '00852') $country_code = '86';

                if ($password !== $password1) return $this->failJSON('两次输入的密码不一致');
                if (!preg_match("/^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,16}$/", $password)) return $this->failJSON('请输入6~16位字母数字密码');

                if ($pay_password !== $pay_password1) return $this->failJSON('支付密码不一致');
                if (strlen($password) < 6)  return $this->failJSON('密码长度不能小于6');
                if (!preg_match("/^[0-9]{6}$/", $pay_password))  return $this->failJSON('请输入6位数字交易密码');

                $data['password'] = md5($password);
                $data['pay_password'] = md5($pay_password);

                $ret = $m->field('id')->where('phone', $phone)->find();
                if($ret) return $this->failJSON('当前手机号已注册，请前往登陆');

                $invite_code = $this->_post('invite_code');
                if (!empty($invite_code)) {
                    //获取邀请者id
                    $invite_user_id = $m->getInfoByInviteCode($invite_code);
                    if (!empty($invite_user_id)) {
                        $data['pid'] = $invite_user_id['id']; //邀请者id
                    } else {
                        return $this->failJSON('邀请人不存在');
                    }
                }else{
                    return $this->failJSON('请输入邀请码');
                }
                $type = 1; //验证码类型 : 注册
                if($verify_code==565656){
                    $_verify = 1;
                }else{
                    $verifyM = new \addons\member\model\VericodeModel();
                    $_verify = $verifyM->VerifyCode($verify_code, $phone, $type, $country_code);
                }
                if (empty($_verify)) {
                    return $this->failJSON(lang('LOGIN_CODE_WRONG'));
                }
                $m->startTrans();
                $data['phone'] = $phone;
                $data['country_code'] = $country_code;
                $data['username'] = $phone;
//            $data['username'] = $username;
                $data['register_time'] = NOW_DATETIME;
                if(!empty($invite_user_id['pid_path'])){
                    $pid_path = $invite_user_id['pid_path'].$invite_user_id['id'].',';
                }else{
                    $pid_path = $invite_user_id['id'].',';
                }
                $data['pid_path'] = $pid_path;
                $data['invite_code'] = createRandCode(6);
                $user_id = $m->add($data);
                if ($user_id > 0) {
//                $achM = new \addons\member\model\MemberAchievement;
//                $achM->createPhy($user_id);
//                $res = $achM->addPhy($pid_path,1,1);
//                if (!$res) {
//                    $m->rollback();
//                    return $this->failData("添加人员失败");
//                }
                    $configM = new \addons\config\model\BalanceConf();
                    $balanceM = new \addons\member\model\Balance();
                    $type_list = $configM->getDataList(-1, -1, '', 'id', 'id asc');
                    foreach ($type_list as $k => $type) {
                        $_balance['user_id'] = $user_id;
                        $_balance['type'] = $type['id'];
                        $_balance['update_time'] = NOW_DATETIME;
                        $balanceM->add($_balance);
                    }

                    $m->commit();
                    return $this->successJSON(lang('LOGIN_REG_SUCCESS'));
                } else {
                    $m->rollback();
                    return $this->failJSON(lang('LOGIN_REG_FAIL'));
                }
            } catch (\Exception $ex) {
                $m->rollback();
                return $this->failJSON($ex->getMessage());
            }
        }else{
            $sysConfM = new \web\common\model\sys\SysParameterModel();
            $url = $sysConfM->getValByName('app_download_url');
            $this->assign('download_url',$url);
            $this->assign('invite_code',$this->_get('invite_code'));
            return $this->fetch();
        }
    }

    public function emailRegister(){
        if(IS_POST){
            $m = new \addons\member\model\MemberAccountModel();
            try {
                $phone = trim($this->_post('phone',true));
//                if (!preg_match("/^1[34578]{1}\d{9}$/", $phone)) return $this->failJSON('请输入正确的手机号');
                $password = trim($this->_post('password',true));
                $password1 = trim($this->_post('password1',true));
                $verify_code = trim($this->_post('verify_code',true));
                $country_code = $this->_post('country_code', true, 'int')??86;
                $pay_password = trim($this->_post('pay_password',true));
                $pay_password1 = trim($this->_post('pay_password1',true));
                if ($country_code == '00886' || $country_code == '00852') $country_code = '86';

                if ($password !== $password1) return $this->failJSON('两次输入的密码不一致');
                if (!preg_match("/^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,16}$/", $password)) return $this->failJSON('请输入6~16位字母数字密码');

                if ($pay_password !== $pay_password1) return $this->failJSON('支付密码不一致');
                if (strlen($password) < 6)  return $this->failJSON('密码长度不能小于6');
                if (!preg_match("/^[0-9]{6}$/", $pay_password))  return $this->failJSON('请输入6位数字交易密码');

                $data['password'] = md5($password);
                $data['pay_password'] = md5($pay_password);

                $ret = $m->field('id')->where('email', $phone)->find();
                if($ret) return $this->failJSON('当前邮箱已注册，请前往登陆');

                $invite_code = $this->_post('invite_code');
                if (!empty($invite_code)) {
                    //获取邀请者id
                    $invite_user_id = $m->getInfoByInviteCode($invite_code);
                    if (!empty($invite_user_id)) {
                        $data['pid'] = $invite_user_id['id']; //邀请者id
                    } else {
                        return $this->failJSON('邀请人不存在');
                    }
                }else{
                    return $this->failJSON('请输入邀请码');
                }
                $type = 1; //验证码类型 : 注册
                if($verify_code==565656){
                    $_verify = 1;
                }else{
                    $verifyM = new \addons\member\model\VericodeModel();
                    $_verify = $verifyM->VerifyCode($verify_code, $phone, $type, $country_code);
                }
                if (empty($_verify)) {
                    return $this->failJSON(lang('LOGIN_CODE_WRONG'));
                }
                $m->startTrans();
                $data['phone'] = $phone;
                $data['country_code'] = $country_code;
                $data['username'] = $phone;
//            $data['username'] = $username;
                $data['register_time'] = NOW_DATETIME;
                if(!empty($invite_user_id['pid_path'])){
                    $pid_path = $invite_user_id['pid_path'].$invite_user_id['id'].',';
                }else{
                    $pid_path = $invite_user_id['id'].',';
                }
                $data['pid_path'] = $pid_path;
                $data['invite_code'] = createRandCode(6);
                $user_id = $m->add($data);
                if ($user_id > 0) {
//                $achM = new \addons\member\model\MemberAchievement;
//                $achM->createPhy($user_id);
//                $res = $achM->addPhy($pid_path,1,1);
//                if (!$res) {
//                    $m->rollback();
//                    return $this->failData("添加人员失败");
//                }
                    $configM = new \addons\config\model\BalanceConf();
                    $balanceM = new \addons\member\model\Balance();
                    $type_list = $configM->getDataList(-1, -1, '', 'id', 'id asc');
                    foreach ($type_list as $k => $type) {
                        $_balance['user_id'] = $user_id;
                        $_balance['type'] = $type['id'];
                        $_balance['update_time'] = NOW_DATETIME;
                        $balanceM->add($_balance);
                    }

                    $m->commit();
                    return $this->successJSON(lang('LOGIN_REG_SUCCESS'));
                } else {
                    $m->rollback();
                    return $this->failJSON(lang('LOGIN_REG_FAIL'));
                }
            } catch (\Exception $ex) {
                $m->rollback();
                return $this->failJSON($ex->getMessage());
            }
        }else{
            $sysConfM = new \web\common\model\sys\SysParameterModel();
            $url = $sysConfM->getValByName('app_download_url');
            $this->assign('download_url',$url);
            $this->assign('invite_code',$this->_get('invite_code'));
            return $this->fetch();
        }
    }

    /**
     * 获取和判断用户编号
     * @param int $user_id
     * @return bool
     */
    public function getUserCode($user_id = 0){
        $accountM = new \addons\member\model\MemberAccountModel();
//        if($user_id > 1000){
        $user_code = rand(10000000, 99999999);
//        }else{
//            $temp_num = 100000000;
//            $new_num = $user_id + $temp_num;
//            $user_code =  substr($new_num,1,8);;
//        }
        $find_data = $accountM->where(['user_code' => $user_code])->find();
        if($find_data){
            $this->getUserCode($user_id);
        }
        $re = $accountM->where(['id' => $user_id])->update(['user_code' => $user_code]);
        if(!$re){
            return  false;
        }else{
            return true;
        }
    }

    public function getCountryCode(){
        $countryM = new \addons\config\model\CountryCode;
        $ctry_list = $countryM->getDataList(-1, -1, '', 'id,country,mobile_prefix', 'id asc');
        return $this->successJSON($ctry_list);
    }

    public function getCode(){
        $country_code = $this->_post('country_code', true, 'int');
        if($country_code == '00886' || $country_code == '00852'){
            $country_code = '86';
        }
        $phone = $this->_post('phone');
//        if ($phone == '18787570174') return $this->failJSON('error');
        $time = 120;
        $type = 1; //注册验证码
        $m = new \addons\member\model\VericodeModel();
        $unpass_code = $m->hasUnpassCode($phone, $type, $country_code);
        if (!empty($unpass_code)) {
            return $this->failJSON(lang('API_CODE_EXISTS'));
        }
//        $smsDayCount = $m->getTodaySmsCount($phone);
//        if ($smsDayCount > 5) return $this->failJSON('已超过每日短信上限');
        try {
            //发送验证码 $country_code .
//            $res = \addons\member\utils\ChSms::send($phone);
            $res = \addons\member\utils\Sms::send($phone);
//            $res = \addons\member\utils\ClSms::send($phone);
            if (!$res['success']) {
                return $this->failJSON($res['message']);
            }
            //保存验证码
            $pass_time = date('Y-m-d H:i:s', strtotime("+" . $time . " seconds"));
            $data['country_code'] = $country_code;
            $data['phone'] = $phone;
            $data['code'] = $res['code'];
            $data['type'] = $type;
            $data['pass_time'] = $pass_time; //过期时间
            $result = $m->add($data);
            if (empty($result)) {
                return $this->failJSON(lang('API_CODE_FAIL')); //写入数据库失败
            }
            unset($res['code']);
            return $this->successJSON($res['message']);
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 短信验证
     */
    public function getEmailVerifyCode() {
        $email = $this->_post('email');
        if (!$email)
            return $this->failJSON(lang('LOGIN_CELL_PHONE_NUMBER'));
        $type = $this->_post('type');
        $time = 120;
        if (empty($type))
            $type = 1; //登陆或注册
        $m = new \addons\member\model\VericodeModel();
//        $unpass_code = $m->hasUnpassCode($phone, $type);
//        if (!empty($unpass_code)) {
//            return $this->failJSON(lang('API_CODE_EXISTS'));
//        }
        try {
            //发送验证码
//            $res = \addons\member\utils\Sms::send($phone);
//            $res = \addons\member\utils\ChSms::send($phone);
            $pattern = '/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i';
            if (!preg_match($pattern, $email))
                return $this->failJSON(lang('API_INCORRECT_EMAIL_FORMAT'));
            $res = (new \addons\member\model\VericodeModel())->sendEmail($email);
            if (!$res['success']) {
                return $this->failJSON($res['message']);
            }
//            $res = \addons\member\utils\ClSms::send($phone);
//            $res['success'] = true;
//            $res['code'] = 111111;
            if ($res['success']) {
                $res['success'] = true;
                $res['message'] = '邮箱发送成功';
                if (!empty($res['code'])) {
                    //保存验证码
                    $pass_time = date('Y-m-d H:i:s', strtotime("+" . $time . " seconds"));
                    $data['phone'] = $email;
                    $data['code'] = $res['code'];
                    $data['type'] = $type;
                    $data['pass_time'] = $pass_time; //过期时间
                    $ret = $m->add($data);
                    unset($res['code']);
                }
                return $this->successJSON($res['message']);
            } else {
                return $this->failJSON($res['message']);
            }
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }



    /**
     * 输出错误JSON信息。
     * @param type $message
     */
    protected function failJSON($message) {
        $message = lang($message);
        $jsonData = array('success' => false, 'message' => $message);
        $json = json_encode($jsonData, true);
        echo $json;
        exit;
    }

    /**
     * 输出成功JSON信息
     * @param type $data
     */
    protected function successJSON($data = NULL, $msg = "success") {
        $jsonData = array('success' => true, 'data' => $data, 'message' => $msg);
        $json = json_encode($jsonData, 1);
        echo $json;
        exit;
    }

}
